package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.Claims;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.hmdp.constant.JwtClaimsConstant;
import com.hmdp.dto.UserDTO;
import com.hmdp.properties.JwtProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constant.JwtClaimsConstant.USER_ID;
import static com.hmdp.constant.RedisConstants.LOGIN_USER_KEY;
import static com.hmdp.constant.RedisConstants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {

//    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final JwtProperties jwtProperties; // 直接通过构造器注入

    // 注入StringRedisTemplate , 由于是自己 手动创建的，所以需要提供一个构造器
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate, JwtProperties jwtProperties) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.jwtProperties = jwtProperties;
    }

//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        // 1.获取 Session（不存在则自动创建）
////        HttpSession session = request.getSession();
//        // 改进: 1.1 TODO 获取请求头中的token
//        String token = request.getHeader("authorization");
//        if (StrUtil.isBlank(token)) {
//            return true;
//        }
//        // 2.从 Session 中获取用户信息("user"是用户实体对象，通过setAttribute方法存入Session)
////        Object user =  session.getAttribute("user");
//        // 改进 2.1 TODO 基于TOKEN获取redis中的用户
//        String key  = LOGIN_USER_KEY + token;
//        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
//        //3.判断用户是否存在(登录)
////        if ( user == null ) {
//        //3.1 改进 TODO 判断用户是否存在(登录)
//        if ( userMap.isEmpty() ) {
//            //4.不存在，拦截，返回401状态码
//            response.setStatus(401);
//            return false;
//        }
//        //  4.5. TODO 改进 将查询到的hash数据转为UserDTO
//        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
//        //5.存在，保存用户信息到Threadlocal
////        UserHolder.saveUser((UserDTO) user);
//        UserHolder.saveUser(userDTO);
//        // 5.5  TODO 刷新token有效期
//        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);
//        //6.放行
//        return true;
//        //return HandlerInterceptor.super.preHandle(request, response, handler);
//    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的token

        String token = request.getHeader(jwtProperties.getUserTokenName());
        if (StrUtil.isBlank(token)) {
            return true;
        }
        //byte[] keyBytes = jwtProperties.getUserSecretKey().getBytes(StandardCharsets.UTF_8); // 推荐明确指定编码
        JWT jwt = JWTUtil.parseToken(token); // 正确顺序

        // 方式1：直接获取userId字段值
        // 通过 Hutool 的 JSON 工具类转换
        JSONObject payload = jwt.getPayloads();
        Long userId = payload.getLong(JwtClaimsConstant.USER_ID);
//        Object userIdObj = jwt.getPayload(JwtClaimsConstant.USER_ID);
//        Long userId = userIdObj != null ? Long.valueOf(userIdObj.toString()) : null;
        //Long userId = (Long) jwt.getPayload(USER_ID);
        //Long userId =  claims.get(JwtClaimsConstant.USER_ID,Long.class);

        // 2.基于userId获取redis中的用户
        String key  = LOGIN_USER_KEY + userId;
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
        // 3.判断用户是否存在
        if (userMap.isEmpty()) {
            return true;
        }
        // 4.判断token是否一致,防止有以前生成的jwt，仍然能够登录
        String jwttoken = userMap.get("jwttoken").toString();
        if(!jwttoken.equals(token)){
            return true;
        }
        // 5.将查询到的hash数据转为UserDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        // 6.存在，保存用户信息到 ThreadLocal
        UserHolder.saveUser(userDTO);
        // 7.刷新token有效期
        stringRedisTemplate.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        //7.移除用户信息
        UserHolder.removeUser();
    }



//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }

}